package com.atswust.shake.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author liushuai
 * @create 2022-02-06 16:39
 */

@Component
public class JWTutils {
        private  static final String secret="shake-secret" ;
        private   static final Long expiration=604800L;
        /**
         * 生成token  header.payload.sing
         */
        public static String getToken(Map<String, String> map) {
//            Calendar instance = Calendar.getInstance();
//            instance.add(Calendar.DATE, 7);//默认7天过期
            //创建jwt builder
            JWTCreator.Builder builder = JWT.create();
            //payload
            map.forEach((k, v) -> {
                builder.withClaim(k, v);
            });
            //指定令牌过期时间
            String token = builder.withExpiresAt(new Date(System.currentTimeMillis()+expiration*1000))
                    .sign(Algorithm.HMAC256(secret));
            return token;
        }

        /**
         * 验证token 合法性
         */
        public static DecodedJWT verify(String token) {
            return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        }

    /**
     * 获取token信息方法
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        return verify;
    }
    /**
     *
     */
    public  static String getAccountByToken(String token){
        DecodedJWT verify = verify(token);
        String account = verify.getClaim("account").asString();
        return  account;
    }
}